package com.taokatao.cardmee.business;

import android.animation.Animator;
import android.app.ActivityOptions;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewAnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.sdk.android.feedback.impl.FeedbackAPI;
import com.alibaba.sdk.android.feedback.util.IWxCallback;
import com.bumptech.glide.Glide;
import com.google.gson.reflect.TypeToken;
import com.taokatao.cardmee.App;
import com.taokatao.cardmee.BaseActivity;
import com.taokatao.cardmee.BusEvent;
import com.taokatao.cardmee.C;
import com.taokatao.cardmee.R;
import com.taokatao.cardmee.SplashActivity;
import com.taokatao.cardmee.Utils;
import com.taokatao.cardmee.WebActivity;
import com.taokatao.cardmee.api.ApiManager;
import com.taokatao.cardmee.api.RespInfo;
import com.taokatao.cardmee.api.RespWrapper;
import com.taokatao.cardmee.api.SubscriberAdapter;
import com.taokatao.cardmee.api.model.UploadPhotoInfo;
import com.taokatao.cardmee.api.security.ServiceUrlProvider;
import com.taokatao.cardmee.business.profile.ProfileAboutActivity;
import com.taokatao.cardmee.business.profile.ProfileAppShareActivity;
import com.taokatao.cardmee.business.profile.ProfileInfoEditActivity;
import com.taokatao.cardmee.business.profile.ProfileMessageActivity;
import com.taokatao.cardmee.business.profile.ProfileReceiveActivity;
import com.taokatao.cardmee.business.profile.ProfileSettingsActivity;
import com.taokatao.cardmee.common.widget.AlertDialog;
import com.taokatao.cardmee.common.widget.SheetDialog;
import com.taokatao.cardmee.db.MessageDao;
import com.taokatao.cardmee.db.UserDao;
import com.taokatao.cardmee.db.model.Card;
import com.taokatao.cardmee.db.model.Message;
import com.taokatao.cardmee.db.model.User;

import java.io.File;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;
import jp.wasabeef.glide.transformations.BlurTransformation;

public class ProfileLayout extends LinearLayout implements View.OnClickListener {

    @BindView(R.id.v_fit_2) View vFit2;
    @BindView(R.id.i_menu) ImageView iMenu;
    @BindView(R.id.i_avatar) ImageView iAvatar;
    @BindView(R.id.t_my_card_count) TextView tMyCardCount;
    @BindView(R.id.t_collect_card_count) TextView tFavoriteCardCount;
    @BindView(R.id.l_receive) View lReceive;
    @BindView(R.id.l_about) View lAbout;
    @BindView(R.id.l_share_my_card) View lShareMyCard;
    @BindView(R.id.l_contact) View lContact;
    @BindView(R.id.l_feedback) View lFeedback;
    @BindView(R.id.i_feedback_unread) View iFeedbackUnread;
    @BindView(R.id.l_invite) View lInvite;
    @BindView(R.id.l_splash) View lSplash;
    @BindView(R.id.v_avatar_background) ImageView vAvatarBackground;
    @BindView(R.id.i_menu_message) ImageView iMenuMessage;
    @BindView(R.id.i_menu_message_unread) View iMenuMessageUnread;


    Callback callback;

    private AlertDialog dlgShareMyCard;
    private SheetDialog dlgAvatarBackground;

    public ProfileLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        ButterKnife.bind(this, LayoutInflater.from(context).inflate(R.layout.layout_profile, this));

        final int statusBarHeight = Utils.calcStatusBarHeight(context);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            vFit2.getLayoutParams().height += statusBarHeight;
            ((MarginLayoutParams) iMenu.getLayoutParams()).topMargin += statusBarHeight;

            ((MarginLayoutParams) iMenuMessage.getLayoutParams()).topMargin += statusBarHeight;
            ((MarginLayoutParams) iMenuMessageUnread.getLayoutParams()).topMargin += statusBarHeight;
        }

    }

    public void setCallback(Callback cb) {
        callback = cb;
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        if (!isInEditMode()) {
            loadProfileInfo();
        }
    }

    @Override
    @OnClick({R.id.i_avatar, R.id.l_invite, R.id.l_about, R.id.l_contact, R.id.l_feedback, R.id.l_share_my_card, R.id.l_splash, R.id.i_menu, R.id.v_avatar_background, R.id.i_menu_message, R.id.l_receive})
    public void onClick(View v) {
        if (v == iAvatar) {
            Utils.onMobEvent(getContext(), "clickHeadOfMain");
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                BaseActivity holder = (BaseActivity) getContext();

                ActivityOptions options =
                        ActivityOptions.makeSceneTransitionAnimation(holder, v, "avatar");
                Intent intent = new Intent(holder, ProfileInfoEditActivity.class);
                holder.startActivity(intent, options.toBundle());
                Animator anim =
                        ViewAnimationUtils.createCircularReveal(vAvatarBackground, vAvatarBackground.getWidth(), 0,
                                (float) Math.sqrt(vAvatarBackground.getWidth() * vAvatarBackground.getWidth() +
                                        vAvatarBackground.getHeight() * vAvatarBackground.getHeight()), 0);
                anim.start();
            } else {
                Intent intent = new Intent(getContext(), ProfileInfoEditActivity.class);
                getContext().startActivity(intent);
            }

        } else if (v == lInvite) {
            Utils.onMobEvent(getContext(), "clickInviteFriendsOfPersonalCenter");
            Intent intent = new Intent(getContext(), ProfileAppShareActivity.class);
            getContext().startActivity(intent);
        } else if (v == lAbout) {
            Intent intent = new Intent(getContext(), ProfileAboutActivity.class);
            getContext().startActivity(intent);
        } else if (v == lFeedback) {
            Utils.onMobEvent(getContext(), "clickFeedbackOfAbout");
            FeedbackAPI.openFeedbackActivity(getContext());
            FeedbackAPI.clearFeedbackUnreadCount(getContext(), null, null);
            iFeedbackUnread.setVisibility(View.GONE);
        } else if (v == lContact) {
            try {
                Utils.onMobEvent(getContext(), "clickContactCustomerOfPersonalCenter");
                String url = "mqqwpa://im/chat?chat_type=wpa&uin=2898316367";
                getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
            } catch (Exception e) {
                e.printStackTrace(); // ActivityNotFoundException
                new AlertDialog.Builder(getContext()).setTitle("提示").setMessage("客服QQ：2898316367")
                        .setPositiveButton("好", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        }).create().show();
            }
        } else if (v == lShareMyCard) {
            Utils.onMobEvent(getContext(), "clickShareMyCardOfPersonalCenter");
            showShareMyCardDialog();
        } else if (v == lSplash) {
            Utils.onMobEvent(getContext(), "clickUnderstandCardMeeOfPersonalCenter");
            Intent intent = new Intent(getContext(), SplashActivity.class);
            intent.putExtra("extra_is_just_finish", true);
            getContext().startActivity(intent);
        } else if (v == iMenu) {
            Intent intent = new Intent(getContext(), ProfileSettingsActivity.class);
            getContext().startActivity(intent);
        } else if (v == vAvatarBackground) {
            // next version do that
            // showAvatarBackgroundDialog();
        } else if (v == iMenuMessage) {
            Intent intent = new Intent(getContext(), ProfileMessageActivity.class);
            getContext().startActivity(intent);
            iMenuMessageUnread.setVisibility(View.INVISIBLE);
        } else if (v == lReceive) {
            Intent intent = new Intent(getContext(), ProfileReceiveActivity.class);
            getContext().startActivity(intent);
        }
    }

    public void onEventMainThread(BusEvent event) {
        if (event.type == BusEvent.TYPE_MAIN_THREAD) {
            switch (event.action) {
                case BusEvent.USER_PROFILE_INFO_CHANGED:
                    loadProfileInfo();
                    break;
                case BusEvent.CARD_REFRESHED:
                    refreshCardCountInfo();
                    break;
                case BusEvent.MESSAGE_SYS_BY_PUSH:
                    iMenuMessageUnread.setVisibility(View.VISIBLE);
                    break;
            }
        }
    }

    private void loadProfileInfo() {
        User currUser = App.i().getCurrUser();
        if (currUser != null) {
            Utils.logd("loadProfileInfo load user avatar url[%s]", currUser.getHeadImgUrl());
            if (!TextUtils.isEmpty(currUser.getHeadImgUrl())) {
                Glide.with(getContext()).load(currUser.getHeadImgUrl()).placeholder(R.mipmap.avatar_default)
                        .centerCrop().bitmapTransform(App.i().getCropCircleTransformation()).into(iAvatar);
            }

            Utils.logd("loadProfileInfo load user avatar background url[%s]", currUser.getBackImgIcon());
            if (!TextUtils.isEmpty(currUser.getBackImgIcon())) {
                Glide.with(getContext()).load(currUser.getBackImgIcon()).placeholder(R.mipmap.profile_avatar_background)
                        .centerCrop().bitmapTransform(new BlurTransformation(getContext(), 10)).into(vAvatarBackground);
            }

            refreshCardCountInfo();

            FeedbackAPI.getFeedbackUnreadCount(getContext(), null, new IWxCallback() {
                @Override
                public void onSuccess(Object... objects) {
                    try {
                        int feedbackUnreadCount = (int) objects[0];
                        iFeedbackUnread.setVisibility(feedbackUnreadCount > 0 ? View.VISIBLE : View.GONE);
                    } catch (Exception ignored) {
                    }
                }

                @Override
                public void onError(int i, String s) {
                }

                @Override
                public void onProgress(int i) {
                }
            });

            requestGetMyMessageList();
        }
    }

    private void refreshCardCountInfo() {
        int myCardCount = (callback != null ? callback.obtainMyCardCount() : 0);
        int myCollectCount = (callback != null ? callback.obtainMyCollectCount() : 0);
        tMyCardCount.setText(myCardCount + "张");
        tFavoriteCardCount.setText(myCollectCount + "张");
        Utils.logd("refreshCardCountInfo tMyCardCount:%d#collectCardCount:%d", myCardCount, myCollectCount);
    }

    private void showShareMyCardDialog() {
        if (dlgShareMyCard == null) {
            dlgShareMyCard = new AlertDialog.Builder(getContext())
                    .setTitle("提示")
                    .setMessage("共享会员卡之后，您的会员卡将会出现在【发现】栏目中，方便别人的同时，也可以让别人帮自己累积积分！\n\n您还需确认该卡是您本人所有，并愿意分享到卡蜜发现，如果确认，请联系客服！\n\n友情提示：请谨慎分享含有储值功能的会员卡，以免造成额外损失。")
                    .setNegativeButton("联系客服", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            try {
                                Utils.onMobEvent(getContext(), "clickContactCustomerOfPersonalCenter");
                                String url = "mqqwpa://im/chat?chat_type=wpa&uin=2898316367";
                                getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                            } catch (Exception e) {
                                e.printStackTrace(); // ActivityNotFoundException
                                Utils.showToast("尚未安装QQ客户端");
                            }
                        }
                    })
                    .setPositiveButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    }).create();
        }
        dlgShareMyCard.show();
    }

    private void showAvatarBackgroundDialog() {
        if (dlgAvatarBackground == null) {
            dlgAvatarBackground = new SheetDialog.Builder(getContext()).setTitle("更换封面")
                    .addMenu("拍照", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            ((BaseActivity) getContext()).openCamera(75, 32, 750, 320, "profile_avatar_background");
                        }
                    }).addMenu("从相册选择", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            ((BaseActivity) getContext()).openPhotos(75, 32, 750, 320, "profile_avatar_background");
                        }
                    }).create();
        }
        dlgAvatarBackground.show();
    }

    public void setAvatarBackground(String localPath) {
        Glide.with(getContext()).load(localPath).bitmapTransform(new BlurTransformation(getContext(), 10)).into(vAvatarBackground);

        ApiManager.i().uploadAvatar(getContext(), null, new File(localPath), new SubscriberAdapter<RespWrapper<UploadPhotoInfo>>() {
            @Override
            public void onNext(RespWrapper<UploadPhotoInfo> o) {
                super.onNext(o);
                if (o.code == C.http.RESULT_CODE_SUCCESS) {
                    String url = o.decode(UploadPhotoInfo.class).backIconUrl;

                    User currUser = App.i().getCurrUser();
                    if (currUser != null) {
                        UserDao userDao = App.i().getUserDBSession().getUserDao();
                        currUser.setBackImgIcon(url);
                        userDao.insertOrReplaceInTx(currUser);

                        int sGender = currUser.getSex() != null ? currUser.getSex() : User.GENDER_FEMALE;
                        String sRealName = currUser.getRealName();
                        long sBirthday = currUser.getBirthday() != null ? currUser.getBirthday() : 0;

                        ApiManager.i().updateUser(getContext(), currUser.getUuid(),
                                "",
                                "",
                                url,
                                sRealName,
                                sBirthday,
                                sGender, 0, new SubscriberAdapter<RespWrapper<RespInfo>>() {
                                }.errorToast(false));
                    }
                }

            }
        }.errorToast(false));
    }

    private void requestGetMyMessageList() {
        long syncStartTime = Utils.spReadLong("api_getMyMessageList", 20161121000000l);
        ApiManager.i().getMyMessageList(getContext(), App.i().getCurrUser().getUuid(), syncStartTime, new SubscriberAdapter<RespWrapper<List<Message>>>() {
            @Override
            public void onNext(RespWrapper<List<Message>> o) {
                super.onNext(o);
                if (o.code == C.http.RESULT_CODE_SUCCESS) {
                    User currUser = App.i().getCurrUser();
                    if (currUser != null) {
                        List<Message> remoteMessageList = o.decode(new TypeToken<List<Message>>() {
                        }.getType());

                        if (remoteMessageList != null) {
                            for (Message m : remoteMessageList){
                                m.setMMessageType(Message.MESSAGE_TYPE_BUSINESS);
                            }
                        }

                        MessageDao messageDao = App.i().getUserDBSession().getMessageDao();
                        List<Message> localBusinessMessageList =  messageDao.queryBuilder().where(MessageDao.Properties.MMessageType.eq(Message.MESSAGE_TYPE_BUSINESS)).list();
                        if (remoteMessageList != null) {
                            Iterator<Message> messageIterator = localBusinessMessageList.iterator();
                            while (messageIterator.hasNext()) {
                                Message c = messageIterator.next();
                                int mirrorIdx = remoteMessageList.indexOf(c);
                                if (mirrorIdx == -1) {
                                } else {
                                    Message mirror = remoteMessageList.get(mirrorIdx);
                                    // Utils.loge("card refresh update mirror [%s]", mirror.toString());
                                    c.refreshProperties(mirror);
                                    // Utils.logd("card refresh update [%s]", c.toString());
                                    messageDao.insertOrReplace(c);
                                    remoteMessageList.remove(mirror);
                                }
                            }
                            messageDao.insertOrReplaceInTx(remoteMessageList);
                        }

                        // 刷新红点信息
                        refreshUnreadMessageCount();
                    }
                }
            }
        });
    }

    private void refreshUnreadMessageCount() {
        MessageDao messageDao = App.i().getUserDBSession().getMessageDao();

        long unreadCount= 0;
        List<Message> messageList = messageDao.queryBuilder().list();
        for (Message m : messageList) {
            if (m.getHadRead() == null || m.getHadRead() == Message.READ_UNREAD) {
                unreadCount++;
                break;
            }
        }

        Utils.logd("unreadCount:" + unreadCount);
        iMenuMessageUnread.setVisibility(unreadCount > 0 ? View.VISIBLE : View.GONE);
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        EventBus.getDefault().unregister(this);
    }

    public interface Callback {
        int obtainMyCardCount();

        int obtainMyCollectCount();
    }
}
